<template>
    <div class="user-profile-container">
        <h2>个人信息</h2>
        <div class="user-avatar">
            <img :src="userInfo.avatarUrl || defaultAvatar" alt="用户头像" />
        </div>
        <div class="user-info">
            <div class="info-item">
                <strong>用户名:</strong> <span>{{ userInfo.username }}</span>
            </div>
            <div class="info-item">
                <strong>邮箱:</strong> <span>{{ userInfo.email }}</span>
            </div>
            <div class="info-item">
                <strong>余额:</strong> <span>{{ userInfo.balance | currency }}</span>
                <button v-if="userInfo.role == 'customer'"
                    style="margin-left: 50px; background-color: #FFD700;letter-spacing: 3px; font-weight: 600; padding: 5px 10px;"
                    @click="showRechargeModal" class="modern-button">充值</button>
            </div>
            <div class="info-item">
                <strong>角色:</strong> <span>{{ displayRole }}</span>
            </div>
        </div>
        <div class="actions">
            <button @click="editProfile">修改个人信息</button>
            <button v-if="userInfo.role == 'customer'" @click="viewOrders">查看订单信息</button>
        </div>

        <!-- 充值金额输入模态弹窗 -->
        <div v-if="isRechargeModalVisible" class="modern-modal">
            <div class="modern-modal-content">
                <div class="modern-modal-header">
                    <h2>充值</h2>
                    <span class="modern-close" @click="closeRechargeModal">&times;</span>
                </div>
                <div class="modern-modal-body">
                    <p>当前余额: {{ userInfo.balance | currency }}</p>
                    <p v-if="errorMessage" class="error-message">{{ errorMessage }}</p>
                    <input v-model.number="rechargeAmount" type="number" placeholder="输入充值金额" class="modern-input" />
                    <button @click="generateQRCode" class="modern-button" :disabled="!!errorMessage">充值</button>
                </div>
            </div>
        </div>

        <!-- 二维码模态弹窗 -->
        <div v-if="isQRCodeModalVisible" class="modern-modal">
            <div class="modern-modal-content">
                <div class="modern-modal-header">
                    <h2>请扫码充值</h2>
                    <span class="modern-close" @click="closeQRCodeModal">&times;</span>
                </div>
                <div class="modern-modal-body">
                    <img :src="rechargeQRCodeUrl" alt="充值二维码" class="modern-qrcode" />
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue';
import { useRouter } from 'vue-router';
import { get, post } from '@/until/request';
import Swal from 'sweetalert2';

const userInfo = ref({});
const defaultAvatar = 'https://xiaoxiongzai.oss-cn-guangzhou.aliyuncs.com/uniapp/avatar/d6abbcd4-5571-4858-8f3d-0ae58970de37.jpg'; // 默认头像路径
const router = useRouter();
const isRechargeModalVisible = ref(false); //充值模态弹窗
const isQRCodeModalVisible = ref(false); //二维码模态弹窗   
const rechargeQRCodeUrl = ref('');  //二维码地址
const rechargeAmount = ref(0);   //充值金额
const errorMessage = ref('');    //错误信息

let pollingInterval;
let pollingTimeout;

onMounted(() => {
    const storedData = localStorage.getItem('login');
    if (storedData) {
        userInfo.value = JSON.parse(storedData);
    }
});

// 计算属性显示角色
const displayRole = computed(() => {
    switch (userInfo.value.role) {
        case 'customer':
            return '用户';
        case 'seller':
            return '销售';
        default:
            return '未知角色';
    }
});

// 监听充值金额的变化
watch(rechargeAmount, (newValue) => {
    if (newValue < 1 || newValue > 99999) {
        errorMessage.value = '请输入1到99999之间的金额';
    } else {
        errorMessage.value = '';
    }
});

// 修改个人信息
function editProfile() {
    router.push({ name: 'EditUserInfo' });
}

// 查看订单信息
function viewOrders() {
    router.push({ name: 'OrderHistory' });
}

// 显示充值模态弹窗
function showRechargeModal() {
    isRechargeModalVisible.value = true;
}

// 关闭充值模态弹窗
function closeRechargeModal() {
    isRechargeModalVisible.value = false;
    errorMessage.value = '';
}

// 关闭二维码模态弹窗
function closeQRCodeModal() {
    clearInterval(pollingInterval);
    clearTimeout(pollingTimeout);
    isQRCodeModalVisible.value = false;
}

// 生成二维码
async function generateQRCode() {
    if (errorMessage.value) return;

    try {
        const response = await get('/api/generatePaymentLink', {
            id: userInfo.value.id,
            amount: rechargeAmount.value
        });
        const qrCodeBase64 = response.data;
        rechargeQRCodeUrl.value = `data:image/png;base64,${qrCodeBase64}`; // 将 Base64 字符串转换为图像 URL
        isQRCodeModalVisible.value = true;
        isRechargeModalVisible.value = false;
        startPolling(); // 开始轮询
    } catch (error) {
        Swal.fire({
            icon: 'error',
            title: '生成二维码失败',
            text: error.message
        });
    }
}

// 开始轮询支付状态
function startPolling() {
    const startTime = Date.now();  //开始时间
    const expectedBalance = userInfo.value.balance + rechargeAmount.value;  //预期余额
    console.log("预期余额：", expectedBalance);
    pollingInterval = setInterval(async () => {
        try {
            const response = await get('/api/pollingBalance', { id: userInfo.value.id });
            // console.log(response);
            const currentBalance = response.data;   //当前余额
            console.log("获取余额：", currentBalance)

            if (currentBalance == expectedBalance) {
                clearInterval(pollingInterval);   //停止轮询
                clearTimeout(pollingTimeout);     //停止超时
                Swal.fire({
                    icon: 'success',
                    title: '支付成功',
                    text: '您的充值已成功处理。'
                });
                closeQRCodeModal();  //关闭二维码模态弹窗
                userInfo.value.balance = currentBalance;   //更新用户余额
                localStorage.setItem('login', JSON.stringify(userInfo.value)); //更新本地存储
            } else if (Date.now() - startTime >= 20000) {
                clearInterval(pollingInterval);
                Swal.fire({
                    icon: 'error',
                    title: '支付超时',
                    text: '未能在规定时间内完成支付。'
                });
                closeQRCodeModal();  //关闭二维码模态弹窗
            }
        } catch (error) {
            console.error('检查余额失败', error);
        }
    }, 3000); // 每3秒检查一次

    // 设置超时
    pollingTimeout = setTimeout(() => {
        clearInterval(pollingInterval);  //停止轮询
        Swal.fire({
            icon: 'error',
            title: '支付超时',
            text: '未能在规定时间内完成支付。'
        });
        closeQRCodeModal();
    }, 20000); // 20秒超时
}
</script>

<style lang="scss" scoped>
.user-profile-container {
    max-width: 700px;
    margin: 1rem auto;
    padding: 0.5rem 2.5rem;
    background-color: #ffffff;
    border-radius: 12px;
    box-shadow: 0 6px 12px rgba(0, 0, 0, 0.15);
    text-align: center;
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;

    .user-avatar {
        margin-bottom: 2rem;

        img {
            width: 150px;
            height: 150px;
            border-radius: 50%;
            object-fit: cover;
            border: 3px solid #eee;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
        }
    }

    .user-info {
        margin-bottom: 2.5rem;
        text-align: left;
        background-color: #f7f7f7;
        padding: 1.5rem;
        border-radius: 8px;
        border: 1px solid #ddd;

        .info-item {
            margin-bottom: 1.2rem;
            font-size: 1.2rem;
            color: #333;
        }
    }

    .actions {
        display: flex;
        justify-content: center;
        gap: 25px;

        button {
            background-color: #007bff;
            color: white;
            padding: 12px 24px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            transition: background-color 0.3s, transform 0.2s;
            font-size: 1rem;

            &:hover {
                background-color: #0056b3;
                transform: translateY(-2px);
            }
        }
    }
}

.modern-modal {
    display: flex;
    justify-content: center;
    align-items: center;
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.7);
    z-index: 1000;
    backdrop-filter: blur(8px);
}

.modern-modal-content {
    background-color: #fff;
    padding: 30px;
    border-radius: 12px;
    width: 90%;
    max-width: 500px;
    box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2);
    position: relative;
}

.modern-modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

.modern-close {
    font-size: 28px;
    cursor: pointer;
    color: #333;
}

.modern-modal-body {
    text-align: center;
}

.modern-input {
    width: 100%;
    padding: 10px;
    margin-top: 10px;
    margin-bottom: 20px;
    border: 1px solid #ddd;
    border-radius: 6px;
    font-size: 16px;
}

.modern-button {
    background-color: #007bff;
    color: white;
    padding: 7px 24px;
    border: none;
    border-radius: 6px;
    cursor: pointer;
    transition: background-color 0.3s, transform 0.2s;
    font-size: 16px;
}

.modern-button:hover {
    background-color: #0056b3;
    transform: translateY(-2px);
}

.modern-qrcode {
    max-width: 100%;
    height: auto;
    margin-top: 20px;
}

.error-message {
    color: red;
    font-size: 14px;
    margin-top: 10px;
}
</style>